<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

require_once(dirname(__FILE__) . "/../common/Logger.php");
require_once(dirname(__FILE__) . "/../common/Common.php");
require_once(dirname(__FILE__) . "/../dbcom/OrderCom.php");
require_once(dirname(__FILE__) . "/../dbcom/ServiceCom.php");
require_once(dirname(__FILE__) . "/../dbcom/C_serviceCom.php");
require_once(dirname(__FILE__) . "/../dbcom/ServiceinfoCom.php");

$logger = new Logger("./../notify.log");
$common = new Common();
$ordercom = new OrderCom();
$servicecom = new ServiceCom();
$serviceinfocom = new ServiceinfoCom();
$cservicecom = new CservicetCom();

$xml = file_get_contents('php://input');

$logger->debug($xml);
$result = $common->getcontent($xml);

$rr = array();
if ($result['result_code'] == 'SUCCESS') {
    $tradeno = $result['out_trade_no'];
    $order = $ordercom->getOrderByTradeno($tradeno);
    if (!$order) {
        $rr['return_code'] = "FAIL";
        $rr['return_msg'] = "CANNOT FIND ORDER";
        $xml2 = $common->toxml($rr);
        $logger->debug($xml2);
        echo $xml2;
        exit();
    }
    $res = $ordercom->changeOrderisPay($order['id'], 1);
    if ($res) {
        
    } else {
        $rr['return_code'] = "ORDER_FAILED";
        $rr['return_msg'] = "CHANGE ISPAY FAILED";
        $xml2 = $common->toxml($rr);
        $logger->debug($xml2);
        echo $xml2;
        exit();
    }
    $servicelist = $serviceinfocom->getServiceinfoByOrderid($order['id']);
    foreach ($servicelist as $v) {
        $cservice = $cservicecom->getCservice($order['customer_id'], $v['service_id']);
        if (!empty($cservice)) {
            $number = $cservice['number'] + $v['total'];
            $res = $cservicecom->changeNumber($order['customer_id'], $v['service_id'], $number);
            if (!$res) {
                $rr['return_code'] = "FAIL";
                $rr['return_msg'] = "UPDATE NUMBER CSERVICE";
                $xml2 = $common->toxml($rr);
                $logger->debug($xml2);
                echo $xml2;
                exit();
            }
        } else {
            $number = $v['total'];
            $res = $cservicecom->addCservice($order['customer_id'], $v['service_id'], $number);
            if (!$res) {
                $rr['return_code'] = "FAIL";
                $rr['return_msg'] = "ADD NUMBER CSERVICE";
                $xml2 = $common->toxml($rr);
                $logger->debug($xml2);
                echo $xml2;
                exit();
            }
        }
    }
    $rr['return_code'] = "SUCCESS";
    $rr['return_msg'] = "OK";
} else {
    $rr['return_code'] = "FAIL";
    $rr['return_msg'] = "REQUEST NOT SUCCESS";
}
$xml1 = $common->toxml($rr);
$logger->debug($xml1);
echo $xml1;
exit();
